
#import "RZTabBar.h"
#import "SPCommon.h"
#import "SPVerticalLayoutBtn.h"

@interface RZTabBar()
/**当前选中的按钮*/
@property (nonatomic,weak) SPVerticalLayoutBtn *selectedButton;

@end

@implementation RZTabBar

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self){
        //只需要设置一次的属性
        
    }
    return self;
    
}

- (NSMutableArray *)tabBarButtons
{
    if(_tabBarButtons == nil){
        _tabBarButtons = [NSMutableArray array];
    }
    return _tabBarButtons;
}


//在TabBar里添加按钮
- (void)addTabBarButtonWithItem:(UITabBarItem *)item
{
    //1 创建按钮
//    RZTabBarCustomButton *button = [[RZTabBarCustomButton alloc] init];
    SPVerticalLayoutBtn *button = [SPVerticalLayoutBtn new];
    //2 添加
    [self addSubview:button];
    //添加按钮到数组中
    [self.tabBarButtons addObject:button];
    
    //3 设置数据
    button.item = item;
    
    //4 监听按钮点击
    [button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchDown];
    
    //5 默认第一个按钮为选中
    if(self.tabBarButtons.count == 1){
        [self clickButton:button];
    }
    
}


//监听按钮点击
- (void)clickButton:(SPVerticalLayoutBtn *)button
{
    //NSLog(@"btn.tag=%ld",(long)button.tag);
    
    //1.1 让当前选中的按钮取消选中
    self.selectedButton.selected = NO;
    //1.2 让新点击的按钮选中
    button.selected = YES;
    //1.3 让新点击的按钮成为选中按钮
    self.selectedButton = button;
    
    //2 通知代理
    if([self.delegate respondsToSelector:@selector(tabBar:didSelectedButtonFrom:to:)])
    {
        [self.delegate tabBar:self didSelectedButtonFrom:self.selectedButton.tag to:button.tag];
    }
    
}




//布局子控件
- (void)layoutSubviews
{
    [super layoutSubviews];
    
    CGFloat height = self.frame.size.height;
    CGFloat width = self.frame.size.width;
    
    
    //设置frame
    CGFloat buttonY = 0;
    CGFloat buttonW= width / self.subviews.count;
    CGFloat buttonH = height;
    
    for (int index = 0; index < self.tabBarButtons.count; index++) {
        //1 拿到每个按钮
        SPVerticalLayoutBtn *button = self.tabBarButtons[index];
        
        //2 设置按钮的frame
        CGFloat buttonX = index * buttonW;
        
        button.frame = CGRectMake(buttonX, buttonY, buttonW, buttonH);
        
        //3 给按钮绑定tag
        button.tag = index;
        
    }
    
}

@end
